const { useEffect, useState, useContext, createContext } = React;
const { Menu, SubMenu } = antd;

const defaultIdentityState = { type: null, id: null, username: null };

var IdentityContext = createContext(defaultIdentityState);

var prefix = '/web';

function deepFindFirstPath(routes = []) {
    if (!routes.length) return '';
    const first = routes[0];
    return Array.isArray(first.children) ? first.path + deepFindFirstPath(first.children) : first.path;
}

function App() {
    const [identity, setIdentity] = useState(defaultIdentityState);
    const [routes, setRoutes] = useState([]);
    const fetchUserInfo = () => {
        request
            .get('/user/userInfo')
            .then(res => {
                if (res) {
                    setIdentity({
                        ...res,
                        type: res.type,
                    });
                    const newRoutes = routeMapping[typeMapping[res.type]] || [];
                    if (location.pathname === prefix || location.pathname === prefix + '/') {
                        location.href = prefix + deepFindFirstPath(newRoutes);
                    }
                    setRoutes(newRoutes);
                } else {
                    // location.href = '/login';
                }
            })
            .catch(err => {
                console.log(err);
            });
    };

    useEffect(() => {
        console.log('1');
        fetchUserInfo();
    }, []);

    const renderRoute = (route, prefix) => {
        return route.map(item => {
            if (item.children) {
                return (
                    <Menu.SubMenu title={item.title} key={prefix + item.path}>
                        {renderRoute(item.children, prefix + item.path)}
                    </Menu.SubMenu>
                );
            }
            return <Menu.Item key={prefix + item.path}>{item.title}</Menu.Item>;
        });
    };

    const pathname = location.pathname;

    return (
        <div style={{ display: 'flex', height: '100%' }}>
            <Menu
                selectedKeys={[pathname]}
                onClick={({ item, key, keyPath }) => {
                    location.href = key;
                }}
                style={{ width: 256 }}
                theme='dark'
                mode='inline'>
                {renderRoute(routes, prefix)}
            </Menu>

            <IdentityContext.Provider value={identity}>
                <div style={{ flex: '1 1' }}>
                    <Load></Load>
                </div>
            </IdentityContext.Provider>
        </div>
    );
}
